package com.knxhd.utils;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.knxhd.pojo.LlmModelConfig;

import cn.hutool.core.util.StrUtil;
import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.model.language.StreamingLanguageModel;
import dev.langchain4j.model.openai.OpenAiStreamingChatModel;
import dev.langchain4j.model.openai.OpenAiStreamingChatModel.OpenAiStreamingChatModelBuilder;

/*
 * @author: tianluhua
 * @Date: 2025-07-15 10:30:37
 * @Description: langchain4j工具类
 * @version: V1.0.0
 */
public class LangChain4jUtil {

    /**
     * 构造langchain4j的模型
     * 
     * @param llmModelConfig 模型配置类
     * @return {@link StreamingLanguageModel}
     */
    public static StreamingChatModel streamingLanguageModelBulider(LlmModelConfig llmModelConfig) {
        // 设置基础参数
        OpenAiStreamingChatModelBuilder builder = OpenAiStreamingChatModel.builder()
                .baseUrl(llmModelConfig.getApi())
                .modelName(llmModelConfig.getModelId());

        String header = llmModelConfig.getHeader();

        
        // 设置请求头
        if (StrUtil.isNotBlank(header)) {
            Map<String, String> customHeaderMap = new HashMap<>();
            JSONObject headerJSON = JSONObject.parseObject(header);
            for (Map.Entry<String, Object> entry : headerJSON.entrySet()) {
                if (StrUtil.isNotBlank(entry.getKey()) && StrUtil.isNotBlank(entry.getValue() + "")) {
                    customHeaderMap.put(entry.getKey(), entry.getValue() + "");
                }
            }
            builder.customHeaders(customHeaderMap);
        }
        

        return builder.build();
    }

}
